import { Injectable, NotFoundException } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { NpcClusterEntity } from "../entities/npc-cluster.entity";
import { NpcDetailEntity } from "../entities/npc-detail.entity";
import { MapAreaEntity } from "../entities/map-area.entity";

@Injectable()
export class NpcService {
  constructor(
    @InjectRepository(NpcClusterEntity)
    private npcClusterRepository: Repository<NpcClusterEntity>,
    @InjectRepository(NpcDetailEntity)
    private npcDetailRepository: Repository<NpcDetailEntity>,
    @InjectRepository(MapAreaEntity)
    private mapAreaRepository: Repository<MapAreaEntity>
  ) { }

  /**
   * 根据区域ID获取该区域的NPC集群列表
   * @param areaId 区域ID
   * @returns NPC集群列表，格式对齐标准数据
   */
  async getNpcsByAreaId(areaId: number): Promise<any[]> {
    try {
      const clusters = await this.npcClusterRepository.find({
        where: { areaId, isActive: 1 },
        order: { id: "ASC" },
      });

      // 转换为标准格式
      return clusters.map((cluster) => ({
        ap: cluster.attackPower,
        id: cluster.id,
        name: cluster.name,
        typeId: cluster.typeId,
      }));
    } catch (error) {
      console.error(`获取区域 ${areaId} 的NPC集群列表失败:`, error);
      return [];
    }
  }

  /**
   * 根据NPC集群ID获取NPC详细信息
   * @param clusterId NPC集群ID
   * @returns NPC详细信息，格式对齐标准数据
   */
  async getNpcDetailById(clusterId: number): Promise<any[]> {
    try {
      const cluster = await this.npcClusterRepository.findOne({
        where: { id: clusterId, isActive: 1 },
        relations: ["details", "area"],
      });

      if (!cluster) {
        throw new NotFoundException(`NPC集群 ID ${clusterId} 不存在`);
      }

      // 获取集群下的所有NPC详情
      const details = await this.npcDetailRepository.find({
        where: { clusterId, isActive: 1 },
        order: { id: "ASC" },
      });

      // 转换为标准格式
      return details.map((detail) => ({
        descr: detail.description,
        img: detail.image,
        lvl: detail.level,
        name: detail.name,
        num: detail.count,
      }));
    } catch (error) {
      console.error(`获取NPC集群 ${clusterId} 详细信息失败:`, error);
      throw error;
    }
  }

  /**
   * 获取所有区域的NPC数据（用于数据收集）
   * @returns 所有区域的NPC数据
   */
  async getAllAreaNpcs(): Promise<any[]> {
    try {
      // 查询所有有parent_id的区域
      const areas = await this.mapAreaRepository.find({
        where: { parentId: { $ne: null } as any },
        order: { id: "ASC" },
      });

      const result = [];
      for (const area of areas) {
        const clusters = await this.getNpcsByAreaId(area.id);
        if (clusters.length > 0) {
          result.push({
            area_id: area.id,
            area_name: area.name,
            parent_id: area.parentId,
            npcs: clusters,
          });
        }
      }

      return result;
    } catch (error) {
      console.error("获取所有区域NPC数据失败:", error);
      return [];
    }
  }

  /**
   * 批量创建NPC集群和详情数据
   * @param clusterDataList NPC集群数据列表
   */
  async createNpcClusters(clusterDataList: any[]): Promise<void> {
    try {
      for (const clusterData of clusterDataList) {
        // 检查集群是否已存在
        const existingCluster = await this.npcClusterRepository.findOne({
          where: { id: clusterData.id },
        });

        if (!existingCluster) {
          // 创建集群
          const cluster = this.npcClusterRepository.create({
            id: clusterData.id,
            name: clusterData.name,
            areaId: clusterData.areaId,
            typeId: clusterData.typeId || 1,
            attackPower: clusterData.attackPower || 0,
            isActive: 1,
          });

          await this.npcClusterRepository.save(cluster);
          console.log(`✅ 创建NPC集群: ${cluster.name} (ID: ${cluster.id})`);

          // 创建集群下的NPC详情
          if (clusterData.details && clusterData.details.length > 0) {
            for (const detailData of clusterData.details) {
              const detail = this.npcDetailRepository.create({
                clusterId: cluster.id,
                name: detailData.name,
                description: detailData.description || "暂无描述",
                image: detailData.image || "default.png",
                level: detailData.level || 1,
                count: detailData.count || 1,
                attackPower: detailData.attackPower || 0,
                defense: detailData.defense || 0,
                health: detailData.health || 100,
                expReward: detailData.expReward || 0,
                silverReward: detailData.silverReward || 0,
                dropItems: detailData.dropItems || null,
                isActive: 1,
              });

              await this.npcDetailRepository.save(detail);
              console.log(
                `  ✅ 创建NPC详情: ${detail.name} (集群ID: ${cluster.id})`
              );
            }
          }
        } else {
          console.log(
            `⏭️ NPC集群已存在: ${existingCluster.name} (ID: ${existingCluster.id})`
          );
        }
      }
    } catch (error) {
      console.error("批量创建NPC数据失败:", error);
      throw error;
    }
  }

  /**
   * 根据区域ID获取区域信息
   * @param areaId 区域ID
   * @returns 区域信息
   */
  async getAreaById(areaId: number): Promise<MapAreaEntity | null> {
    try {
      return await this.mapAreaRepository.findOne({
        where: { id: areaId },
      });
    } catch (error) {
      console.error(`获取区域 ${areaId} 信息失败:`, error);
      return null;
    }
  }

  /**
   * 获取NPC统计信息
   * @returns NPC统计信息
   */
  async getNpcStatistics(): Promise<any> {
    try {
      const totalClusters = await this.npcClusterRepository.count({
        where: { isActive: 1 },
      });

      const totalDetails = await this.npcDetailRepository.count({
        where: { isActive: 1 },
      });

      const totalAreas = await this.mapAreaRepository.count({
        where: { parentId: { $ne: null } as any },
      });

      const clustersByType = await this.npcClusterRepository
        .createQueryBuilder("cluster")
        .select("cluster.typeId", "typeId")
        .addSelect("COUNT(*)", "count")
        .where("cluster.isActive = 1")
        .groupBy("cluster.typeId")
        .getRawMany();

      return {
        totalClusters,
        totalDetails,
        totalAreas,
        clustersByType,
      };
    } catch (error) {
      console.error("获取NPC统计信息失败:", error);
      return {
        totalClusters: 0,
        totalDetails: 0,
        totalAreas: 0,
        clustersByType: [],
      };
    }
  }
}
